package com.ygnn.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.ygnn.reggie.common.BaseContext;
import com.ygnn.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//坑点，路径是"/*"，别忘了*
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public  static   final AntPathMatcher PATH_MATCER =new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        //定义不需要处理的请求路径，前端页面可以放行，只是除登录登出的后端拦截就行。
        String [] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/back/View/login.html",
                "/user/sendMsg",
                "/user/login",
                "/back/**"
        };
        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        if(check){
            log.info("本次请求{} 不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录 id为{}",request.getSession().getAttribute("employee"));

//            这里可以设置线程id
            Long Id= (Long) request.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(Id);
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录 id为{}",request.getSession().getAttribute("user"));
            Long Id= (Long) request.getSession().getAttribute("user");
            BaseContext.setThreadLocal(Id);

            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return ;
    }
    //这里是坑点，不能用equals比较
    public  boolean check(String[] urls,String requestUrl){
        for(String url :urls){
            boolean match=PATH_MATCER.match(url,requestUrl);
            if(match){
                return true;
            }
        }
        return false;
    }
}
